package com.edu.juc.cas.atomic;

import com.edu.juc.bean.BankAccount;
import com.edu.juc.bean.MyVar;

import java.util.concurrent.CountDownLatch;

/**
 * 以一种线程安全的方式操作非线程安全对象内的某些字段。
 */
public class AtomicFieldUpdater {
    public static void main(String[] args) {
        BankAccount bankAccount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
//                    bankAccount.deposit(10);
                    bankAccount.deposit(bankAccount, 10);
                }
                countDownLatch.countDown();
            }, "t" + i).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最终余额为: " + bankAccount.getMoney());


        // AtomicReferenceFileUpdater
        MyVar myVar = new MyVar();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
//                myVar.init();
                myVar.setIsInit();
            }, "t" + i).start();
        }
    }
}
